<?php
declare (strict_types = 1);

namespace app\model;

use app\common\model\CacheRefreshHandler;
use app\common\service\redis\PoolRedis;
use app\util\Tools;
use think\Model;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

/**
 * @mixin \think\Model
 */
class AdminStaff extends Model
{
    const SCHOOL_SEX_GROUP = 'staff_group:';

    /*
     * 班主任、任课教师、主任（分部门）、校领导（正、副校长）、门卫、宿管
     */
    const TYPE_ARR = [0=>'学生',1=>'宿管',2=>'门卫',3=>'任课教师',4=>'班主任',5=>'主任',6=>'校领导'];
    const STUDENT = 0; // 学生
    const STAFF = 1; // 宿管
    const GATEKEEPER = 2; // 门卫
    const TEACHER = 3; // 任课教师
    const HEADMASTER = 4; // 班主任
    const DIRECTOR = 5; // 主任（分部门）
    const LEADER = 6; // 校领导（正、副校长）

    const AUDIT_WAITING = 0; // 待审核
    const AUDIT_PASS = 1;   // 审核通过
    const AUDIT_REFUSE = 2; // 审核拒绝
    //
    protected $name = 'admin_staff';
    protected $autoWriteTimestamp = true;

    public function staffData(): HasOne {
        return $this->hasOne('AdminStaffData', 'staff_id', 'id')->bind(['last_login_time']);
    }

    /*废弃*/
//    public function superSim(): HasOne {
//        return $this->hasOne('AdminSuperSim', 'staff_id', 'id')->where('is_delete', 0)->bind([
//            'sim_uid' => 'nfc_id',
//            'sim_activate_time' => 'create_time'
//        ]);
//    }

    public function icCard(): hasMany {
        return $this->hasMany('AdminStaffIcCard', 'staff_id', 'id')
            ->where('is_delete', 0)
            ->hidden(['is_delete','update_time']);
    }

    public function checkIn(): HasMany {
        return $this->hasMany('AdminCheckInRecord', 'staff_id', 'id');
    }

    public function school() {
        return $this->belongsTo(AdminSchool::class, 'school_id')->where('is_delete', 0)->bind([
            'school_name' => 'name'
        ]);
    }

    public function class() {
        return $this->belongsTo(AdminClass::class, 'class_id')->where('is_delete', 0)->bind([
            'class_name' => 'name',
            'headmaster_id' => 'staff_id'
        ]);
    }

    /*废弃*/
//    public function dormitory(): BelongsTo {
//        return $this->belongsTo(AdminDormitory::class, 'dormitory_id')->where('is_delete', 0)->bind([
//            'dormitory_name' => 'name'
//        ]);
//    }

    /*废弃*/
//    public function student(): BelongsTo {
//        return $this->belongsTo(AdminStudentDormitory::class, 'student_dormitory_id')->where('is_delete', 0)->bind([
//            'student_dormitory_name' => 'name'
//        ]);
//    }

    public function getDormitoryArrAttr($value,$data)
    {
        return explode(",", $data['dormitory_id']);
    }

    public function getTypeTextAttr($value,$data)
    {
        $type = self::TYPE_ARR;
        return $type[$data['type']];
    }

    public function getStatusTextAttr($value,$data)
    {
        $status = [0=>'待审核',1=>'审核通过',2 => '审核拒绝'];
        return $status[$data['status']];
    }

    public function getPermissionAttr($value,$data)
    {
        return $data['permission'] ? (array)json_decode($data['permission'], true) : [];
    }

    // 判断是否已毕业，是返回true
    public function getExpireFlagAttr($value,$data)
    {
        if ($data['graduate_time'] == '') {
            return false;
        }
        $graduate_day = Tools::getNextMonth($data['graduate_time']);
        $endTime = strtotime($graduate_day[0]." 00:00:00");
        if ($endTime < time()) {
            return true;
        }
        return false;
    }

    public static function onAfterInsert($staff)
    {
        // 南华工贸9月20号开始注册的全部设置为会员用户
        if($staff->getAttr('school_id') == 22) {
            AdminStaff::update(['user_level'=>1], ['id' => $staff->getAttr('id')]);
        } else {
            // 是否为会员用户
            $phonePool = AdminStaffPhonePool::where('phone','=',$staff->getAttr('phone'))->find();
            if ($phonePool || $staff->getAttr('type') != 0){
                AdminStaff::update(['user_level'=>1], ['id' => $staff->getAttr('id')]);
            }
        }

        $redis = PoolRedis::instance();
        $key = self::SCHOOL_SEX_GROUP.$staff->getAttr('school_id');
        $redis->hIncrBy($key, "{$staff->getAttr('sex')}:{$staff->getAttr('type')}", 1);
    }

    public static function onBeforeWrite($staff)
    {
        // 年级分配
        if($staff->entrance_time) {
            $staff->grade = substr($staff->entrance_time, 0, 4);
        }
    }

    public static function onAfterWrite($staff)
    {
        // 软删除后处理
        if ($staff->getAttr('is_delete') == 1) {
            $where = [
                'staff_id' => $staff->getAttr('id'),
                'school_id' => $staff->getAttr('school_id'),
                'is_delete' => 0
            ];
            $redis = PoolRedis::instance();
            // 删除IC卡号
            $redis->hDel("smartCards", $staff->getAttr('smart_card'));
            // 删除SIM卡号
            $redis->hDel("smartCards", $staff->getAttr('sim_card'));
            // 删除授权宿舍号
            $cardList = AdminStaffIcCard::where($where)->select();
            foreach ($cardList as $card) {
                $card->is_delete = 1;
                $card->save();
                // 删除IC卡号
                $redis->hDel("smartCards", $card->ic_card);
            }

            // 删除在线密码
            CacheRefreshHandler::onLinePwDel($staff->getAttr('uuid'));
            // 用户构成统计数据调整
            $data = [
                'school_id' => $staff->getAttr('school_id'),
                'sex' => $staff->getAttr('sex'),
                'type' => $staff->getAttr('type'),
            ];
            $redis = PoolRedis::instance();
            // 学校用户构成数量调整
            $redis->hIncrBy(AdminStaff::SCHOOL_SEX_GROUP.$data['school_id'],"{$data['sex']}:{$data['type']}", -1);
        }
    }

    // 用户构成数量 redis key => staff_group:{school_id} field => {sex}:{type} value => {统计数量}
    public static function setAmountBySchool()
    {
        $redis = PoolRedis::instance();
        $data = AdminStaff::where('is_delete', 0)
            ->field('school_id,sex,type,count(id) as total')
            ->group('school_id,sex,type')->select();
        $redis->multi(\Redis::PIPELINE);
        foreach ($data as $datum) {
            $key = self::SCHOOL_SEX_GROUP.$datum['school_id'];
            $redis->hSet($key, "{$datum['sex']}:{$datum['type']}", $datum['total']);
        }
        $redis->exec();
    }

}
